package com.demo.pojo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.*;
import java.util.stream.Collectors;

public class ZoneUtils {
    public static List<Zone> buildTree1(List<Zone> zoneList) {
        List<Zone> result = new ArrayList<>();
        for (Zone zone : zoneList) {
            if (zone.parentId.equals("0")) {
                result.add(zone);
                setChildren(zoneList, zone);
            }
        }
        return result;
    }

    public static void setChildren(List<Zone> list, Zone parent) {
        for (Zone zone : list) {
            if (parent.id.equals(zone.parentId)) {
                parent.children.add(zone);
            }
        }
        if (parent.children.isEmpty()) {
            return;
        }
        for (Zone zone : parent.children) {
            setChildren(list, zone);
        }
    }


    public static List<Zone> buildTree2(List<Zone> zoneList) {
        List<Zone> result = new ArrayList<>();
        for (Zone zone : zoneList) {
            if (zone.parentId.equals("0")) {
                result.add(zone);
            }
            for (Zone child : zoneList) {
                if (child.parentId.equals(zone.id)) {
                    zone.addChildren(child);
                }
            }
        }
        return result;
    }


    public static List<Zone> buildTree3(List<Zone> zoneList) {
        System.out.println(JSONObject.toJSONString(zoneList));
        Map<String, List<Zone>> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(Zone::getParentId));
        List<Zone>  Zlist = new ArrayList<>();
        zoneList.forEach(zone->   {
            Zone z = new Zone();
                 z.setId(zone.getId());
                z.setName(zone.getName());
                z.setParentId(zone.getParentId());
                z.setChildren(zone.getChildren());
                z.setOrderBy(zone.getOrderBy());
                List<Zone> zones = zoneByParentIdMap.get(zone.getId());
                zone.setChildren(zones);
                z.setChildren(zone.getChildren());
            Zlist.add(z);


        });

        List<Zone> collect = zoneList.stream().sorted(Comparator.comparing(Zone::getOrderBy)).filter(v -> v.parentId.equals("0")).collect(Collectors.toList());
        System.out.println("初始的对象的数据"+JSONObject.toJSONString(zoneList));
        System.out.println("对象的数据"+JSONObject.toJSONString(collect));
        System.out.println("处理后的对象的数据"+JSONObject.toJSONString(Zlist));
        return collect;
}

}
